<script lang="es6">
'use strict';

<% const namespace = dir.replace(new RegExp(`^${name}`), '').length ? '.' + dir.replace(/\//g, '.') : '' %>
const Controller = require('egg').Controller;

class <%=_.capitalize(name)%>Controller extends Controller {
  async index() {
    const ctx = this.ctx;
    const { <%= name %> } = ctx.service<%= namespace %>
    const data = await <%=name%>.find(ctx.query);
    ctx.success({ data });
  }

  async show() {
    const ctx = this.ctx;
    const { <%= name %> } = ctx.service<%= namespace %>
    const data = await <%=name%>.findOne(ctx.params);
    ctx.success({ data });
  }

  async create() {
    const ctx = this.ctx;
    const { <%= name %> } = ctx.service<%= namespace %>
    ctx.validate({
      <% attributes.forEach(element => { %>
        <%= element.name %>: {
          type: '<%= element.params.type %>',
          required: <%= element.params.required %>,
          unique: <%= element.params.unique %>,
          <% let max = element.params.max || element.params.maxLength; %>
          <% if(max || max == 0) { %>
          max: <%= max %>,
          <% } %>
          <% let min = element.params.min || element.params.minLength; %>
          <% if(min || min == 0) { %>
          mim: <%= min %>,
          <% } %>
        },
      <% });%>
    });
    try {
      const id = await <%=name%>.create(ctx.request.body);
      const data = {
        id,
      };
      ctx.success({ data });
    } catch (error) {
      ctx.error({ detail: error });
    }
  }

  async update() {
    const ctx = this.ctx;
    const { <%= name %> } = ctx.service<%= namespace %>
    ctx.validate({
      <% attributes.forEach(element => { %>
        <%= element.name %>: {
          type: '<%= element.params.type %>',
          required: false,
          unique: <%= element.params.unique %>,
          <% let max = element.params.max || element.params.maxLength; %>
          <% if(max || max == 0) { %>
          max: <%= max %>,
          <% } %>
          <% let min = element.params.min || element.params.minLength; %>
          <% if(min || min == 0) { %>
          mim: <%= min %>,
          <% } %>
        },
      <% });%>
    });
    try {
      const params = Object.assign({ id: ctx.params.id }, ctx.request.body);
      const data = await <%=name%>.update(params);
      ctx.success({ data });
    } catch (error) {
      ctx.error({ detail: error });
    }
  }

  async destroy() {
    const ctx = this.ctx;
    const { <%= name %> } = ctx.service<%= namespace %>
    const data = await <%=name%>.destroy(ctx.params);
    ctx.success({ data });
  }
}

module.exports = <%=_.capitalize(name)%>Controller;
</script>
